let wins = [];

const getBounds = (x, y) => {
  let displayMatching = utools.getDisplayNearestPoint({x,y});
  let display = utools.getPrimaryDisplay();
  let displayMatchingScaleFactor =  displayMatching.scaleFactor;
  let displayScaleFactor =  display.scaleFactor;

  let difference = displayScaleFactor - displayMatchingScaleFactor;
  return function (width, height){
    if(difference > 0){
      width = parseInt(width * (1 + difference));
      height = parseInt(height * (1 + difference));
      return {
        x, y, width, height
      }
    }else if(difference < 0){
      width = parseInt(width / (1 - difference));
      height = parseInt(height / (1 - difference));
      return {
        x, y, width, height
      }
    }else{
      return {
        x,
        y,
        width,
        height
      }
    }
  }
}

const calculatePosition = (info) => {
  const { sound, fullScreen, remark, randomImg , urls} = info;
  const display = utools.getAllDisplays();
  return display.map((item, index)=>{
    let bound = item.bounds;
    let width = fullScreen ? item.bounds.width : item.bounds.width / 2;
    let height = fullScreen ? item.bounds.height : item.bounds.height / 2;
    let x = bound.x + (fullScreen ? 0 : width / 2);
    let y = bound.y + (fullScreen ? 0 : height / 2);
    let obj = getBounds(x,y)(width, height);
    return {
      ...obj,
      sound,
      remark,
      fullScreen,
      randomImg,
      urls
    }
  })
}


const createPopup = (bounds, i) => {
  let url = location.href.split("/").at(-2);
  let {x, y, width, height, sound, remark, fullScreen,randomImg, urls} = bounds;
  return new Promise((resolve, reject) => {
    let ubWindow = utools.createBrowserWindow(
      './common/html/popup.html',
      {
        title: 'popup',
        skipTaskbar: true,
        frame: false,
        backgroundColor: "rgba(255,255,255,0)",
        transparent: true,
        titleBarStyle: "hidden",
        resizable: false,
        width,
        height,
        x,
        y,
        webPreferences: {
          preload: "./" + url + "/preload.js",
          spellcheck: false,
        },
      },
      () => {
        ubWindow.show();
        ubWindow.setBackgroundColor("rgba(255,255,255,0)");
        // ubWindow.webContents.openDevTools();
        ipcRenderer.sendTo(ubWindow.webContents.id, "senderId");
        ipcRenderer.sendTo(ubWindow.webContents.id, "init", {
          sound,
          remark,
          randomImg,
          urls,
          index: i
        });
        ubWindow.setAlwaysOnTop(true, 'pop-up-menu')
        if(fullScreen){
          ubWindow.setFullScreen(true) 
        }
        wins.push(ubWindow);
        resolve(ubWindow);
      }
    )
  })
 
}

const debounce = function (func, wait){
  let timeout;
  let arr = [];
  return function (...args) {
    arr.push(...args)
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, [arr]);
      arr = [];
    }, wait);
  }
}


window.openPopup = debounce(
  async (info) => {
    for (let index = 0; index < info.length; index++) {
      const element = info[index];
      let bounds = calculatePosition(element);
      let win
      for(let i = 0; i < bounds.length; i++){
        let bound = bounds[i];
        win = await createPopup(bound, i);
      }
    }
  },800
)

ipcRenderer.on("win", (event, type) => {
  if(!wins.length)return;
  switch (type) {
    case "close":
      wins.forEach(item => {
        item.destroy();
      });
      wins = [];
      break;
    // case "setEmojin":
      
    default:
      break;
  }
});


window.closePopupWin = () => {
  if(wins.length){
    wins.forEach(item => {
      item.destroy();
    });
    wins = [];
  }
}
